//
//  YMOAuthViewController.swift
//  YMWeiBo
//
//  Created by mimi on 16/7/20.
//  Copyright © 2016年 mimi. All rights reserved.
//

import UIKit
import AFNetworking

class YMOAuthViewController: UIViewController {
    
    override func loadView() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        let url = NSURL(string: urlString)
        guard let u = url else{
            return
        }
        let request = NSURLRequest(URL: u)
        webView.loadRequest(request)
        webView.delegate = self
        view = webView
        
        self.navigationController?.navigationBar.addSubview(progressView)
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI ()
    }
    //        MARK: - =========== 响应事件 ===========
    //取消
    func cancelClick() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    func autoFillClick() {
        let jsString = "document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPasswd)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    //        MARK: - ===========  设置UI  ==============
    func setupUI () {

        
        
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, targe: self, action: #selector(YMOAuthViewController.cancelClick))
        
        navigationItem.rightBarButtonItem = YMBarButtonItem(title: "自动填充", imgName: nil, targe: self, action: #selector(YMOAuthViewController.autoFillClick))
        
    }
    
    
    
    
    //        MARK: - ==========  属性声明  =============
    
    
    
    
    
    
    
    
    
    //        MARK: -============= 懒加载控件 =============
 
    private lazy var webView:UIWebView = UIWebView()
    
    private lazy var progressView:YMProgressView = YMProgressView()
}



extension YMOAuthViewController:UIWebViewDelegate{
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        progressView.starAnim()
    }
    
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        progressView.endAnim()
    }
    
    //加载错误
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    /*
     监听webView 将要加载的request
     - 其有返回值
     - 如果返回为true 代表继续加载
     - 如果返回为false 带包要停止加载
     - 默认如果不实现该方法 默认为true
     
     */
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 请求的url字符串
        let urlString = request.URL?.absoluteString
        // 判断urlString 是否为nil 而且他的前缀为回调页
        if let u = urlString where u.hasPrefix(APPREDIRECT_URI) {
            // url 的请求参数
            let query = request.URL?.query
            if let q = query {
                // 获取code
                let code = q.substringFromIndex("code=".endIndex)
                print(code)
                
                
                print(code)
                print(code)
               
            NSNotificationCenter.defaultCenter().postNotificationName(WBSwiftRootViewControllerNoti, object: nil)
                
                YMUserAccountViewModel.sharedTools.loadUserAccount(code, isSuccess: { (isSucc) in
                    
                    if !isSucc {
        return
                    }
                    
                    self.dismissViewControllerAnimated(false, completion: { 
                        //发通知 告知appdelegate 更改跟控制器
//NSNotificationCenter.defaultCenter().postNotificationName(WBSwiftRootViewControllerNoti, object: nil)
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwiftRootViewControllerNoti, object: nil)
                    })
                })
                return false
            }
            
        }
        return true
    }
}












//网络请求数据

extension YMOAuthViewController{
    //请求accessToken数据
    func getUserAccount(code:String){
        
        YMNetworkTools.sharedTools.oauthLoadAccount(code, success: { (response) in
            //转为模型
            guard let res = response as? [String: AnyObject] else{
                return
            }
            
            let userAccount = YMUserAccount(dic: res)
            
            print("请求成功后:\(userAccount)")
            
            self.getUserInfo(userAccount)
            }) { (error) in
                 print("请求失败后")
        }
        

    }
    //请求用户信息
    
    func getUserInfo(userAccount:YMUserAccount) {

        YMNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) in
            guard let res = response as? [String : AnyObject] else{
                return
            }
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
            print("请求成功后:\(userAccount)")
            }) { (error) in
                print("请求成功后:\(error)")
        }

}
}













